package cn.jx.asc.user.controller;

import cn.jx.asc.socket.InstructAndResult;
import cn.jx.asc.user.pojo.*;
import cn.jx.asc.user.service.UserService;
import cn.jx.asc.user.vo.DataShow;
import com.alibaba.fastjson.JSON;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller("classiFicationController")
@RequestMapping("/Classfic")
public class ClassiFicationController {

    @Autowired
    private UserService userService;

    SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");


    /**
     * @author LaiWeiXing
     * @date 2018/6/21 15:55
     * @describe 添加区域
     */
    @RequestMapping("/addArea")
    @ResponseBody
    public String addArea(HttpServletRequest request) {
        //获取到区域名和用户id
        String areaName = request.getParameter("areaName");
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //封装一个Region区域对象
        Region region = new Region();
        region.setRegionName(areaName);
        region.setUserId(userId);
        int row = userService.addRegion(region);
        if (row > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/21 15:55
     * @describe 删除区域
     */
    @RequestMapping("/deleteArea")
    @ResponseBody
    public String deleteArea(HttpServletRequest request) {
        //获取当前区域id
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        if (regionId != null) {
            int row = userService.deleteRegionByRegionId(regionId);
            System.out.println(row);
            if (row > 0) {
                return "success";
            } else {
                return "fail";
            }
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/21 20:44
     * @describe 修改区域名
     */
    @RequestMapping("/updateArea")
    @ResponseBody
    public String updateArea(HttpServletRequest request) {
        //获取到区域id和修改后的区域名
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        String regionName = request.getParameter("areaName");
        //封装一个Region区域对象
        Region region = new Region();
        region.setRegionId(regionId);
        region.setRegionName(regionName);
        int row = userService.updateAreaName(region);
        if (row > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 9:10
     * @describe 根据用户id获取到区域集合，并转换成json格式返回
     */
    @RequestMapping("/regionNameToJson")
    @ResponseBody
    public String regionNameToJson(HttpServletRequest request) {
        //获取到当前用户的userId
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据userId查询当前用户管理的区域
        List<Region> regionList = null;
        if (userId != null) {
            regionList = userService.selectAllByUserId(userId);
            String regionListJsonStr = JSON.toJSONString(regionList);
            return regionListJsonStr;
        }
        return "fail";
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 14:33
     * @describe 获取到管理员id下的种植种类集合，并转换成json格式返回
     */
    @RequestMapping("/cropTypeListToJson")
    @ResponseBody
    public String croupTypeListToJson(HttpServletRequest request) {
        //查找管理员id下的专家方案集合
        List<Plan> planList = userService.findPlanListByUserId(100000003);
        if (!planList.isEmpty()) {
            //将集合转换成json格式
            String planListJsonStr = JSON.toJSONString(planList);
            System.out.println(planListJsonStr);
            return planListJsonStr;
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/22 16:13
     * @describe 添加组
     */
    @RequestMapping("/addGroup")
    @ResponseBody
    public String addGroup(HttpServletRequest request) {
        //获取到表单数据
        String groupName = request.getParameter("groupName");
        String croupType = request.getParameter("cropType");
        String plantTime = request.getParameter("plantTime");
        String regionName = request.getParameter("regionName");
        String regionIdStr = request.getParameter("regionId");
        String sensorName = request.getParameter("sensorName");
        //根据区域id查找到该区域对象
        Integer regionId = Integer.valueOf(regionIdStr);
        //封装一个Group对象
        Group group = new Group();
        group.setGroupName(groupName);
        group.setCroupType(croupType);
        try {
            group.setPlantTime(dataFormat.parse(plantTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        group.setRegionId(regionId);
        //添加组
        int row = userService.insertGroup(group);
        Integer groupId = userService.findLastGroupId();
        if (row > 0) {
            //封装一个Sensor对象
            Sensor sensor = new Sensor();
            sensor.setSensorName(sensorName);
            sensor.setTimeInterval((short) 30);
            sensor.setGroupId(groupId);
            //添加传感器
            int row2 = userService.insertSensor(sensor);
            if (row2 > 0) {
                return "success";
            } else {
                return "fail";
            }
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/24 19:49
     * @describe 根据组id查找一个Group对象
     */
    @RequestMapping(value = "/findGroupByGroupId", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findGroupByGroupId(HttpServletRequest request) {
        //接收传输过来的groupId
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        //查找group对象
        Group group = userService.findGroupByGroupId(groupId);
        System.out.println("group-----------" + group);
        return JSON.toJSONString(group);
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/24 21:29
     * @describe 修改组
     */
    @RequestMapping("/updateGroup_android")
    @ResponseBody
    public String updateGroup(HttpServletRequest request) {
        //获取到表单数据
        String groupName = request.getParameter("groupName");
        String croupType = request.getParameter("cropType");
        String plantTime = request.getParameter("plantTime");
        /*String regionName = request.getParameter("regionName");*/
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = Integer.valueOf(regionIdStr);
        //封装Group对象
        Group group = new Group();
        group.setGroupId(groupId);
        group.setGroupName(groupName);
        group.setCroupType(croupType);
        try {
            group.setPlantTime(dataFormat.parse(plantTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        group.setRegionId(regionId);
        int row = userService.updateGroup(group);
        System.out.println("row-------------" + row);
        if (row > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/25 9:21
     * @describe 删除组
     */
    @RequestMapping("/deleteGroup")
    @ResponseBody
    public String deleteGroup(HttpServletRequest request) {
        //获取到传输过来的id值
        String groupIdStr = request.getParameter("groupId");
        String sensorIdStr = request.getParameter("sensorId");
        Integer groupId = Integer.valueOf(groupIdStr);
        Integer sensorId = Integer.valueOf(sensorIdStr);
        //删除组
        int row = userService.deleteGroup(groupId);
        System.out.println("row-------" + row);
        if (row > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/25 20:47
     * @describe 根据区域id获取组集合
     */
    @RequestMapping(value = "/findGroupListByRegionId", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findGroupListByRegionId(HttpServletRequest request) {
        String regionIdStr = request.getParameter("regionId");
        Integer regionId = null;
        if (regionIdStr != null || regionIdStr != "") {
            regionId = Integer.valueOf(regionIdStr);
        }
        List<Group> groupNameList = userService.findGroupListByRegionId(regionId);
        if (groupNameList != null) {
            String groupNameListJsonStr = JSON.toJSONString(groupNameList);
            return groupNameListJsonStr;
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/25 21:23
     * @describe 添加节点
     */
    @RequestMapping("/addValve")
    @ResponseBody
    public String addValve(HttpServletRequest request) {
        //获取数据
        String nodeCode = request.getParameter("nodeCode");
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        //封装一个Valve对象
        Valve valve = null;
        //定义一个变量记录插入数量
        int count = 0;
        //每插入一个节点，阀门表中插入四个阀门
        for (int i = 1; i <= 4; i++) {
            valve = new Valve();
            valve.setValveName(String.valueOf(i));
            valve.setValveState((short) 0);
            valve.setControlType((short) 1);
            valve.setGroupId(groupId);
            valve.setNodeCode(nodeCode);
            userService.addValve(valve);
            count++;
        }
        if (count > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/26 8:32
     * @describe 删除阀门
     */
    @RequestMapping("/deleteValve")
    @ResponseBody
    public String deleteValve(HttpServletRequest request) {
        //接收数据
        String valveIdStr = request.getParameter("valveId");
        Integer valveId = Integer.valueOf(valveIdStr);
        int row = userService.deleteValveByValveId(valveId);
        if (row > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/26 20:12
     * @describe 查找用户专家方案
     */
    @RequestMapping(value = "/findPlan", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String findPlan(HttpServletRequest request, Model model) {
        //接收页面发送过来的组id
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        System.out.println("groupId--------" + groupId);
        //根据groupId查找一个Group对象
        Group group = userService.findGroupByGroupId(groupId);
        System.out.println("group----" + group);
        //从Group对象中获取到作物种类CropType
        String croupType = group.getCroupType();
        //从session域中获取用户id
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据userId和作物种类查找专家方案
        Plan plan = userService.findPlanByUserIdAndCropType(userId, croupType);
        //如果用户id没有自定义专家方案,那么则使用管理员id下的专家方案
        if (plan == null) {
            plan = userService.findPlanByUserIdAndCropType(100000003, croupType);
        }
        String planJsonStr = JSON.toJSONString(plan);
        return planJsonStr;
    }

    /**
     * @author LaiWeiXing
     * @date 2018/6/29 8:55
     * @describe 查找该专家方案对应的浇灌时间
     */
    @RequestMapping("/findTime")
    @ResponseBody
    public String findTime(HttpServletRequest request, Model model) {
        //接收页面发送过来的组id
        String groupIdStr = request.getParameter("groupId");
        Integer groupId = Integer.valueOf(groupIdStr);
        System.out.println("groupId--------" + groupId);
        //根据groupId查找一个Group对象
        Group group = userService.findGroupByGroupId(groupId);
        System.out.println("group----" + group);
        //从Group对象中获取到作物种类CropType
        String croupType = group.getCroupType();
        //从session域中获取用户id
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据userId和作物种类查找专家方案
        Plan plan = userService.findPlanByUserIdAndCropType(userId, croupType);
        //如果用户id没有自定义专家方案,那么则使用管理员id下的专家方案
        if (plan == null) {
            plan = userService.findPlanByUserIdAndCropType(100000003, croupType);
        }
        //根据专家方案id和生长周期查找到浇灌时间
        Integer planId = plan.getPlanId();
        List<Time> timeList = userService.findTimeListByPlanId(planId);
        System.out.println("timeList---" + timeList);
        //遍历timeList集合,转换开始时间和结束时间格式
        /*for(Time time : timeList){
            Date startTime = time.getStartTime();
            timeFormat.format(startTime);
            Date stopTime = time.getStopTime();
            timeFormat.format(stopTime);
        }*/
        String timeListJsonStr = JSON.toJSONString(timeList);
        System.out.println("timeqqqq1111----" + timeListJsonStr.length());
        for (int i = 0; i < timeListJsonStr.length(); i++) {

        }
        return timeListJsonStr;
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/6/28 15:48
     * @describe 根据组ID查询所有的阀门
     */
    @RequestMapping("/findValveListByGroupId")
    @ResponseBody
    public String findValveListByGroupId(HttpServletRequest request) {
        String ValveId = request.getParameter("groupId");
        List<Valve> valveList = userService.findValveData(ValveId);
        String JsonValveList = JSON.toJSONString(valveList);
        return JsonValveList;
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/6/29 15:03
     * @describe 历史数据查询
     */
    SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @RequestMapping(value = "/historyDataShow") //跳转到历史查询数据页面
    @ResponseBody
    public String dataShow(DataShow dataShow, Model model, HttpServletRequest request) {
        List<Region> regionList = userService.findRegionWithGroup();
        model.addAttribute("regionList", regionList);
        List<Record> recordList = userService.findData(dataShow);  //根据用户查询时间来查询历史数据
        String recordListJson = JSON.toJSONString(recordList);
        model.addAttribute("recordList", recordList);
        return recordListJson;
    }

    /**
     * @author LaiWeiXing
     * @date 2018/7/3 14:56
     * @describe 获取当前数据
     */
    @RequestMapping(value = "/nowData", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String getNowData(Model model) {
        String data = "{\"flags\":\"1\"}";
        org.json.JSONObject jsonData = null;
        try {
            jsonData = new org.json.JSONObject(data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("jsonData---" + jsonData);
        //向终端发送请求数据
        int id = InstructAndResult.sendInstructs(123456, jsonData);
        //获取终端返回的数据
        org.json.JSONObject json = InstructAndResult.getResult(id);
        System.out.println("json----" + json);
        try {
            if (json.getInt("flags") != -1 && json.getInt("flags") != 0) {
                org.json.JSONObject dataJson = json.getJSONObject("data");
                Record record = new Record();
                record.setTemperature((short) dataJson.getInt("tem"));  //环境温度
                record.setTemperatureSoil((short) dataJson.getInt("soilTem"));  //土壤温度
                record.setHumidity((short) dataJson.getInt("hum")); //环境湿度
                record.setHumiditySoil((short) dataJson.getInt("soilTem")); //土壤湿度
                record.setCo2((short) dataJson.getInt("co2"));
                record.setSun(dataJson.getInt("sun"));
                return JSON.toJSONString(record);
            } else {
                return "fail";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/7/6 20:57
     * @describe 给安卓视屏接口
     */

    @RequestMapping("Video")
    public String Video(){
        return "one";
    }


}
